package com.cloud.sample.kafka;

import com.cloud.common.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;

@Slf4j
@Component
public class LogMessageSender {

    private static final String TOPIC_NAME = "log";

    @Autowired
    private KafkaTemplate kafkaTemplate;

    public void send(LogMessage message) {
        ListenableFuture future = kafkaTemplate.send(TOPIC_NAME, message.getUserId(), JsonUtils.toJSONString(message));
        try {
            // 同步等待结果
            future.get();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}
